<?php
// +----------------------------------------------------------------------
// | Desc: [ Better-卡分组 ]
// +----------------------------------------------------------------------
// | Author: huangzhen_20210406
// +----------------------------------------------------------------------

namespace app\common\model;

use app\api\controller\PublicApi;
use think\facade\Db;
use think\facade\Cache;

class Cards extends Common
{
    /**
     * 返回layui的table所需要的格式
     * @param $post
     * @param $user_id
     * @return mixed
     * @throws \think\db\exception\DbException
     */
    public function tableData($post)
    {
        $list_rows  = $post['limit'] ?? config('paginate.list_rows');
        $page       = $post['page'] ?? config('paginate.page');

        $where =[];
        $where[] = ['u.id', '=', $post['user_id']];
        if(isset($post['department']) && !empty($post['department'])){
            $where[] = ['departments_id', '=', $post['department']];
        }
        if(isset($post['card_num']) && !empty($post['card_num'])){
            $where[] = ['pan', 'like', '%'.$post['card_num'].'%'];
        }
        $list = Db::name('lc_cards')->alias('c')
                ->leftJoin('cards_departments cd' ,'cd.id=c.departments_id')
                ->leftJoin('user u','u.id=c.user_id')
                ->where($where)
                ->field('c.*')
                ->order('c.ctime desc')
                ->paginate(['list_rows' => $list_rows, 'page' => $page])
                ->toArray();

        return $result = [
            'code'  => 0,
            'msg'   => lang('get info success'),
            'data'  => $list['data'],
            'count' => $list['total'],
        ];
    }

    public function setCardRemarks($data)
    {
        $card_id    = $data['card_id'];
        $remarks    = $data['remarks'];
        $user_id    = $data['user_id'];

        $card_list  = $this->find($card_id);
        $card_num   = $card_list['card_num'];
        $card_list['remarks'] = $remarks;
        $result     = $card_list->save();

        //记录用户操作
        $logModel = new UserLog();
        $logModel->setLog($user_id , "card set remarks" ,
            ['card_num' => $card_num,'remarks' =>$remarks]);

        return $result;
    }

//-----------------------------------------后端-------------------------------------------------
    /**
     * 返回layui的table所需要的格式
     * @param $post
     * @param $user_id
     * @return mixed
     * @throws \think\db\exception\DbException
     */
    public function tableDataAdmin($post)
    {
        $list_rows  = $post['limit'] ?? config('paginate.list_rows');
        $page       = $post['page'] ?? config('paginate.page');

        $where =[];
        if(isset($post['card_type']) && strlen($post['card_type'])>0){
            $where[] = ['c.card_type', '=', $post['card_type']];
        }
        if(isset($post['card_status']) && strlen($post['card_status'])>0){
            $where[] = ['c.status', '=', $post['card_status']];
        }
        if(isset($post['check_status']) && strlen($post['check_status'])>0){
            $where[] = ['c.check_status', '=', $post['check_status']];
        }
        if(isset($post['bank_type']) && strlen($post['bank_type'])>0){
            if($post['bank_type'] == 3){
                $where[] = ['c.bank_type', '=', 3];
            }else{
                $where[] = ['c.bank_type', '<>', 3];
            }
        }
        if(isset($post['username']) && !empty($post['username'])){
            $where[] = ['username', 'like', '%'.$post['username'].'%'];
        }
        if(isset($post['memo']) && !empty($post['memo'])){
            $where[] = ['c.memo', 'like', '%'.$post['memo'].'%'];
        }
        if(isset($post['card_num']) && !empty($post['card_num'])){
            $where[] = ['c.card_num', 'like', '%'.$post['card_num'].'%'];
        }
        if(isset($post['card_token']) && !empty($post['card_token'])){
            $where[] = ['c.card_token', 'like', '%'.$post['card_token'].'%'];
        }
        if(isset($post['datetime']) && !empty($post['datetime'])){
            $time_list = explode('_' , $post['datetime']);
            $start_time = strtotime($time_list[0] . " 00:00:00");
            $end_time   = strtotime($time_list[1] . " 23:59:59");
            $where[] = ['c.ctime', 'between', "{$start_time},{$end_time}"];
        }
        if(isset($post['card_int']) && strlen($post['card_int'])>0){
            $where[] = ['c.balance', '<', 0];
        }
        $list = Db::name('cards')->alias('c')
            ->leftJoin('user u' ,'u.id=c.user_id')
            ->leftJoin('cards_detail cd','cd.memo=c.memo')
            ->where($where)
            ->field('username,c.*,cd.billing_address,cd.apartment,cd.city,cd.state,cd.zip')
            ->order('c.ctime desc')
            ->paginate(['list_rows' => $list_rows, 'page' => $page])
            ->toArray();
//        if($list['data']){
//            foreach($list['data'] as $k=>&$v){
//                if($v['user_type'] == 1){
//                    $v['used_amount'] = $v['balance'];
//                    $v['balance'] = '';
//                }else{
//                    $v['used_amount'] = '';
//                }
//            }
//        }
        return $result = [
            'code'  => 0,
            'msg'   => lang('get info success'),
            'data'  => $list['data'],
            'count' => $list['total'],
        ];
    }

    public function updateCard($time)
    {
        $list = Db::name('cards')->alias('c')
            ->leftJoin('cards_detail cd','cd.memo=c.memo')
            ->field('c.*,cd.billing_address,cd.apartment,cd.city,cd.state,cd.zip')
            ->where('check_status=0')
            ->limit(10)->select()->toArray();
        Cache::store('redis')->set('updateCard' . $time , 60);
        $cardHeaderType = 'Comdata';
        $result_blog    = false;
        foreach ($list as $v){
            $user_id        = $v['user_id'];
            $card_num       = $v['card_num'];
            $card_balance   = $v['balance_account'];//开卡传卡总金额
            $card_id        = $v['id'];
            $card_type      = $v['card_type'];
            $bank_type      = $v['bank_type'];
            $apartment      = trim($v['apartment']);
            $billing_address = trim($v['billing_address']);
            if(!empty($apartment)){
                $billing_address .= ' '.$apartment;
            }
            //更新卡地址
            $upCardParam =[
                "user_id"       => $user_id,
                "action_type"   => "updateCard",
                "card_type"     => $card_type,
                "bank_type"     => $bank_type,
                "post_param"  => [
                    "card_num"  => $card_num,
                    "address"   => $billing_address,
                    "city"      => $v['city'] ,
                    "state"     => $v['state'] ,
                    "zip"       => $v['zip']
                ]
            ];
            $upCardApi = PublicApi::requestApi($cardHeaderType,$upCardParam);
            $up_card_blog = $upCardApi['blog'];
            if($up_card_blog){
                //限制卡金额
                $upCardLimitsParam =[
                    "user_id"       => $user_id,
                    "action_type"   => "updateCardLimits",
                    "card_type"     => $card_type,
                    "bank_type"     => $bank_type,
                    "post_param"  => [
                        "card_num"      => $card_num,
                        "card_balance"  => $card_balance
                    ]
                ];
                $upCardLimitsApi = PublicApi::requestApi($cardHeaderType,$upCardLimitsParam);
                $up_card_limit_blog = $upCardLimitsApi['blog'];
                if($up_card_limit_blog){
                    //查询过期时间
                    $searchExpDateParam =[
                        "user_id"       => $user_id,
                        "action_type"   => "searchExpDate",
                        "card_type"     => $card_type,
                        "bank_type"     => $bank_type,
                        "post_param"  => [
                            "card_num"      => $card_num
                        ]
                    ];
                    $searchExpDateApi = PublicApi::requestApi($cardHeaderType,$searchExpDateParam);
                    $search_exp_blog  = $searchExpDateApi['blog'];
                    $search_exp_list  = $searchExpDateApi['list'];
                    if($search_exp_blog){
                        //查询Cvv
                        $exp_date     = $search_exp_list['cardExpiration'];
                        $searchCvvParam =[
                            "user_id"       => $user_id,
                            "action_type"   => "searchCvv",
                            "card_type"     => $card_type,
                            "bank_type"     => $bank_type,
                            "post_param"  => [
                                "card_num"  => $card_num,
                                "exp_date"  => $exp_date
                            ]
                        ];
                        $searchCvvApi = PublicApi::requestApi('Comdata3',$searchCvvParam);
                        $search_cvv_blog  = $searchCvvApi['blog'];
                        $search_cvv_list  = $searchCvvApi['list'];
                        if($search_cvv_blog){
                            $cvv = $search_cvv_list['cardSecurityCode'] ?? '';
                            $up_cvv = [
                                'exp_date'      => $exp_date ,
                                'utime'         => getUtcTime()
                            ];
                            if(!empty($cvv)){
                                $up_cvv += [
                                    'cvv'           => $cvv ,
                                    'check_status'  => 1 ,  //1=已开卡
                                ];
                            }
                            $re  = Db::name('cards')->where(['id'=>$card_id])->update($up_cvv);
                            if($re){
                                $result_blog = true;
                            }
                        }else{
                            break;
                        }
                    }else{
                        break;
                    }
                }else{
                    continue;
                }
            }else{
                continue;
            }
        }
        Cache::store('redis')->delete('updateCard' . $time);
        return $result_blog;
    }

    public function updateCardInt($time)
    {
        $list = Db::name('cards')->where('balance < 0')->select()->toArray();
        return $this->repairCard($list,'updateCardInt'. $time);
    }

    public function updateCardIntOnly($time,$id_array)
    {
        $id_value = join(',' , $id_array);
        $list = Db::name('cards')->where("id in({$id_value})")->select()->toArray();
        return $this->repairCard($list,'updateCardIntOnly'. $time);
    }

    public function repairCard($list , $cache_key)
    {
        try {

            Cache::store('redis')->set($cache_key , 60);
            $i              = 0;
            foreach ($list as $v) {
                $ctime = getUtcTime();
                $user_id = $v['user_id'];
                $card_num = $v['card_num'];
                $bank_type= $v['bank_type'];
                $card_num64 = substr($card_num, 0, 6) . ' *** ' . substr($card_num, -4);
                $card_balance = $v['balance'];
                $card_token = $v['card_token'];
                $card_server_amount = $v['server_amount'];
                $card_balance_abs = ceil(abs($card_balance));
                $card_balance_account = $v['balance_account'];
                $card_id = $v['id'];
                $card_type = $v['card_type'];
                $card_status = $v['status'];
                $user_list = Db::name('user')->where(['id' => $user_id])->find();
                $user_balance = $user_list['balance'];
                if ($user_balance - $card_balance_abs >= 0) {
                    $result_user_balance = $user_balance - $card_balance_abs;
                    $result_card_balance = $card_balance + $card_balance_abs;
                    $result_account_balance = $card_balance_account + $card_balance_abs;
                    $desc = $card_num64 . " 余额为负，自动补充余额";
                    $card_log_type = 2; //2-增加余额;3-减少余额
                    $user_cash_log_type = 1; //类型 0,Credit|1,Debit
                    if($bank_type == 3){
                        $update_card_param      = [
                            "user_id"       => $user_id,
                            "action_type"   => 'add_card_balance',
                            "card_num"      => $card_num,
                            "cardGuid"      => $card_token,
                            "request_data"  => [
                                "AmountLimit" => floatval($result_account_balance)
                            ]
                        ];
                        $create_card_api= PublicApi::requestApi('Connexpay',$update_card_param);
                    }else{
                        $update_card_param = [
                            "user_id" => $user_id,
                            "action_type" => 'add_card_balance',
                            "card_type" => $card_type,
                            "bank_type" => $bank_type,
                            "post_param" => [
                                "card_num" => $card_num,
                                "card_balance" => $result_account_balance,
                            ]
                        ];
                        $create_card_api = PublicApi::requestApi('Comdata', $update_card_param);
                    }
                    $return_blog = $create_card_api['blog'];
                    $return_list = $create_card_api['list'];

    //                $responseCode = $return_list['responseCode'] ?? '0'; //正确是 '00000'
                    if ($return_blog) {
                        Db::startTrans();
                        try {
                            //记录卡总金额变化
                            Db::name('cards_log')->save([
                                'card_token' => $card_token,
                                'amount' => $card_balance_abs,
                                'balance' => $result_account_balance,
                                'type' => $card_log_type,
                                'desc' => $desc,
                                'card_type' => $card_type,
                                'ctime' => $ctime
                            ]);
                            //记录钱包记录
                            Db::name('user_cash_log')->save([
                                'user_id' => $user_id,
                                'type' => $user_cash_log_type,
                                'action_type' => 5, //3=消费
                                'amount' => $card_balance_abs,
                                'balance' => $result_user_balance,
                                'desc' => $desc,
                                'card_type' => $card_type,
                                'ctime' => $ctime
                            ]);
                            $cardSetList = UserSet::getCardSet($user_id);
                            $rate = $cardSetList[$bank_type][$card_type]['rate_fund'] ?? 0.05;
                            $server_amount = getSprintf(round($card_balance_abs * $rate,2));
                            $result_user_balance = $result_user_balance - $server_amount;
                            $card_server_amount += $server_amount;
                            //记录钱包卡充值服务费记录
                            Db::name('user_cash_log')->save([
                                'user_id' => $user_id,
                                'type' => $user_cash_log_type,
                                'action_type' => 5, //3=消费
                                'amount' => $server_amount,
                                'balance' => $result_user_balance,
                                'desc' => "充值服务费(余额为负) ($card_num64)",
                                'card_type' => $card_type,
                                'ctime' => $ctime
                            ]);
                            //更新公司用户余额
                            Db::name('user')->where(['id' => $user_id])->update(['balance' => $result_user_balance]);
                            //更新卡余额
                            Db::name('cards')->where(['id' => $card_id])->update([
                                'balance' => $result_card_balance,
                                'balance_account' => $result_account_balance,
                                'server_amount' => $card_server_amount
                            ]);
                            $i++;
                            Db::commit();
                        } catch (\Exception $e) {
                            Cache::store('redis')->delete($cache_key);
                            var_dump($e->getMessage());
                            Db::rollback();
                            break;
                        }
                    }
                }else{
                    if($card_status == 1){
                        if($user_balance > 0 ){
                            $result_user_balance = 0;
                            $result_card_balance = $card_balance + $user_balance;
                            $result_account_balance = $card_balance_account + $user_balance;
                            $desc = $card_num64 . " 余额为负，自动补充余额";
                            $card_log_type = 2; //2-增加余额;3-减少余额
                            $user_cash_log_type = 1; //类型 0,Credit|1,Debit
                            if($bank_type == 3){
                                $update_card_param      = [
                                    "user_id"       => $user_id,
                                    "action_type"   => 'add_card_balance',
                                    "card_num"      => $card_num,
                                    "cardGuid"      => $card_token,
                                    "request_data"  => [
                                        "AmountLimit" => $result_account_balance
                                    ]
                                ];
                                $create_card_api= PublicApi::requestApi('Connexpay',$update_card_param);
                            }else{
                                $update_card_param = [
                                    "user_id" => $user_id,
                                    "action_type" => 'add_card_balance',
                                    "card_type" => $card_type,
                                    "bank_type" => $bank_type,
                                    "post_param" => [
                                        "card_num" => $card_num,
                                        "card_balance" => $result_account_balance,
                                    ]
                                ];
                                $create_card_api = PublicApi::requestApi('Comdata', $update_card_param);
                            }
                            $return_blog = $create_card_api['blog'];
                            $return_list = $create_card_api['list'];
                            //                $responseCode = $return_list['responseCode'] ?? '0'; //正确是 '00000'
                            if ($return_blog) {
                                Db::startTrans();
                                try {
                                    //记录卡总金额变化
                                    Db::name('cards_log')->save([
                                        'card_token' => $card_token,
                                        'amount' => $user_balance,
                                        'balance' => $result_account_balance,
                                        'type' => $card_log_type,
                                        'desc' => $desc,
                                        'card_type' => $card_type,
                                        'ctime' => $ctime
                                    ]);
                                    //记录钱包记录
                                    Db::name('user_cash_log')->save([
                                        'user_id' => $user_id,
                                        'type' => $user_cash_log_type,
                                        'action_type' => 5, //3=消费
                                        'amount' => $user_balance,
                                        'balance' => $result_user_balance,
                                        'desc' => $desc,
                                        'card_type' => $card_type,
                                        'ctime' => $ctime
                                    ]);
                                    $cardSetList = UserSet::getCardSet($user_id);
                                    $rate = $cardSetList[$bank_type][$card_type]['rate_fund'] ?? 0.05;
                                    $server_amount = getSprintf(round($user_balance * $rate,2));
                                    $result_user_balance = $result_user_balance - $server_amount;
                                    $card_server_amount += $server_amount;
                                    //记录钱包卡充值服务费记录
                                    Db::name('user_cash_log')->save([
                                        'user_id' => $user_id,
                                        'type' => $user_cash_log_type,
                                        'action_type' => 5, //3=消费
                                        'amount' => $server_amount,
                                        'balance' => $result_user_balance,
                                        'desc' => "充值服务费(余额为负) ($card_num64)",
                                        'card_type' => $card_type,
                                        'ctime' => $ctime
                                    ]);
                                    //更新公司用户余额
                                    Db::name('user')->where(['id' => $user_id])->update(['balance' => $result_user_balance]);
                                    //更新卡余额
                                    Db::name('cards')->where(['id' => $card_id])->update([
                                        'balance' => $result_card_balance,
                                        'balance_account' => $result_account_balance,
                                        'server_amount' => $card_server_amount
                                    ]);
                                    $i++;
                                    Db::commit();
                                } catch (\Exception $e) {
                                    Cache::store('redis')->delete($cache_key);
                                    var_dump($e->getMessage());
                                    Db::rollback();
                                    break;
                                }
                            }
                        }


                        if($bank_type == 3){
                            $data       = [
                                "user_id"       => $user_id,
                                "action_type"   => "card_suspended",
                                "cardGuid"      => $card_token,
                                "card_num"      => $card_num,
                                "request_data"  => [
                                    "Activated" => false
                                ]
                            ];
                            $repair_card_up_result = PublicApi::requestApi('Connexpay' , $data);
                        }else{

                            $data       = [
                                "user_id"       => $user_id,
                                "action_type"   => "card_suspended",
                                "card_type"     => $card_type,
                                "bank_type"     => $bank_type,
                                "post_param"    => [
                                    "card_num"       => $card_num
                                ]
                            ];
                            $repair_card_up_result = PublicApi::requestApi('Comdata' , $data);
                        }
                        $repair_card_up_blog = $repair_card_up_result['blog'];
                        if($repair_card_up_blog){
                            $update_where = [
                                'status'=>  2,
                                'utime' =>  getUtcTime()
                            ];
                            //更新卡列表状态
                            Db::name('cards')->where(['id'=> $card_id])->update($update_where);
                            //记录会员操作日志
                            $logModel = new UserLog();
                            $logModel->setLog($user_id , 'card_suspended_repair' , ['card_num' => $card_num]);
                        }
                    }
                }
            }
            Cache::store('redis')->delete($cache_key);
            return $i;
        }catch (\Exception $e){
            Cache::store('redis')->delete($cache_key);
            echo 'cards';
            var_dump($e->getMessage());
        }
    }

    public function getCardSet($user_id)
    {
        $list = Db::name('user_set')->where(['user_id' => $user_id])
            ->order('type')->find();
        if(empty($list)){
            $type  = Db::name('user')->where(['id' => $user_id])->value('grade');
            //grade = 2时候，事管理员认证用户， 那么user_set 中type=1就按用户认证状态算
            if($type == 2){
                $type =1;
            }
            $list = Db::name('user_set')->where(['type' => $type , 'user_id'=>0])->find();
        }
        return $list;
    }

    public static function changeCardStatus($data,$manage_id)
    {
        $id_array   = $data['id_array'];
        $type       = $data['type'];

        $success_num =0;
        foreach ($id_array as $v){
            $card_id    = $v;
            $info       = Db::name('cards')->where("is_del !=1")->find($card_id);
            if(!$info){
                continue;
            }
            $card_num   = substr($info['card_num'], -4);
            $card_type  = $info['card_type'];
            $user_id    = $info['user_id'];
            $card_token = $info['card_token'];
            $bank_type  = $info['bank_type'];
            $username   = Db::name('user')->where("id ={$user_id}")->value("username");

            //卡状态：[ OPEN,PAUSED,CLOSED ]
            $type_api       = "";
            $change_status  = "";
            $is_action      = 0;
            switch ($type){
                case 'active':
                    $type_api       = 'card_active';
                    $change_status  = "1";
                    $is_action      = 0;
                    break;
                case 'suspended':
                    $type_api       = 'card_suspended';
                    $change_status  = "2";
                    $is_action      = 1;
                    break;
            }
            if(!$type_api){
                return false;
            }
            if($bank_type == 3){
                $data       = [
                    "user_id"       => $user_id,
                    "action_type"   => $type_api,
                    "cardGuid"      => $card_token,
                    "card_num"      => $info['card_num'],
                    "request_data"  => [
                        "Activated" => ($type_api == 'card_active') ? true : false
                    ]
                ];
                $update_result = PublicApi::requestApi('Connexpay' , $data);
            }else{
                $data       = [
                    "user_id"       => $user_id,
                    "action_type"   => $type_api,
                    "card_type"     => $card_type,
                    "bank_type"     => $bank_type,
                    "post_param"    => [
                        "card_num"       => $info['card_num']
                    ]
                ];
                $update_result = PublicApi::requestApi('Comdata' , $data);
            }

            $update_result_blog = $update_result['blog'];
            if($update_result_blog){
                $update_where = [
                    'status'        =>  $change_status,
                    'is_action'     =>  $is_action,
                    'utime'         =>  getUtcTime()
                ];
                //更新卡列表状态
                Db::name('cards')->where(['id'=> $card_id])->update($update_where);
                //记录管理员操作日志
                ManageLog::saveManageLog([
                    'manage_id' => $manage_id,
                    'desc'      => $type_api,
                    'time'      => getUtcTime(),
                    'content'   => json_encode([
                        'card_num' => $info['card_num'],
                        'username' => $username
                    ])
                ]);
                $success_num += 1;
            }
        }
        return $success_num;
    }

    public static function deleteCards($data,$manage_id)
    {
        $id_array   = $data['id_array'];

        $success_num =0;
        foreach ($id_array as $v){
            $card_id    = $v;
            //获取当前卡余额

            //校验当前余额是否正确
            self::checkCardBalanceApi($card_id,'searchExpDate' , true);
            $card_list          = Db::name('cards')->where("is_del != 1 and status !=3")->find($card_id);
            if(empty($card_list)){
                continue;
            }
            $card_balance           = $card_list['balance'];
            if($card_balance < 0){
                continue;
            }
            $user_id                = $card_list['user_id'];
            //获取当前用户余额
            $user_list              = Db::name('user')->find($user_id);
            $user_balance           = $user_list['balance'];
            $user_name              = $user_list['username'];

            $account_balance        = $card_list['balance_account'];
            $card_num               = $card_list['card_num'];
            $card_token             = $card_list['card_token'];
            $card_type              = $card_list['card_type'];
            $bank_type              = $card_list['bank_type'];
            $ctime                  = getUtcTime();

            if($bank_type == 3){
                $re_account_balance =  $account_balance - $card_balance;
                $AmountLimit        =  1;
                if($re_account_balance >0){
                    //卡总金额比卡余额大 说明卡有消费，这时卡剩余的卡总金额就是已消费金额，这里要更新卡金额限制
                    $AmountLimit        =  $re_account_balance;
                }
                $api_3_param      = [
                    "user_id"       => $user_id,
                    "action_type"   => "del_up_card",
                    "card_num"      => $card_num,
                    "cardGuid"      => $card_token,
                    "request_data"  => [
                        "AmountLimit" => $AmountLimit
                    ]
                ];
                $res = PublicApi::requestApi('Connexpay',$api_3_param);

                $update_card_param      = [
                    "user_id"       => $user_id,
                    "action_type"   => "card_del",
                    "card_num"      => $card_num,
                    "cardGuid"      => $card_token
                ];
                $create_card_api= PublicApi::requestApi('Connexpay',$update_card_param);
            }else{
                //卡总金额比卡余额大 说明卡有消费
                if(($account_balance - $card_balance) > 0){
                    $action_type = 'card_del_unReal';   //软删除，更新卡状态为B=BLOCKED，冻结
                }else{
                    $action_type = 'card_del';          //删除，更新卡状态为C=CLERR，删除
                }
                $update_card_param      = [
                    "user_id"       => $user_id,
                    "action_type"   => $action_type,
                    "card_type"     => $card_type,
                    "bank_type"     => $bank_type,
                    "post_param"  => [
                        "card_num"  => $card_num
                    ]
                ];

                $create_card_api= PublicApi::requestApi('Comdata',$update_card_param);
            }
            $return_blog    = $create_card_api['blog'];

            if($return_blog){
                //记录管理员操作日志
                ManageLog::saveManageLog([
                    'manage_id' => $manage_id,
                    'desc'      => 'manage_card_del',
                    'time'      => getUtcTime(),
                    'content'   => json_encode([
                        'card_num' => $card_num,
                        'username' => $user_name
                    ])
                ]);
                Db::startTrans();
                try{
                    $desc = "银行删除卡(**** " . substr($card_num , -4) . ")";
                    $result_user_balance    =   $user_balance + $card_balance;
                    $result_account_balance =   $account_balance - $card_balance;
                    if($bank_type != 3){
                        if($result_account_balance >0){
                            //卡总金额比卡余额大 说明卡有消费，这时卡剩余的卡总金额就是已消费金额，这里要更新卡金额限制
                            $update_card_param_unreal   = [
                                "user_id"       => $user_id,
                                "action_type"   => 'updateCardLimits',
                                "card_type"     => $card_type,
                                "bank_type"     => $bank_type,
                                "post_param"  => [
                                    "card_balance"  => $result_account_balance,
                                    "card_num"      => $card_num,
                                ]
                            ];
                            PublicApi::requestApi('Comdata',$update_card_param_unreal);
                        }
                    }
                    Db::name('user')->where(['id'=>$user_id])->update(['balance' => $result_user_balance]);
                    $update_card_where = [
                        'balance'           => 0,
                        'balance_account'   => $result_account_balance,
                        'status'            => 3,
                        'is_del'            => ($result_account_balance >0)?1:0, //卡总金额比卡余额大 说明卡有消费,软删除is_del=1
                        'utime'             => $ctime
                    ];
                    Db::name('cards')->where(['id'=>$card_id])->update($update_card_where);
                    //记录卡交易记录
                    Db::name('cards_log')->save([
                        'card_token' => $card_token,
                        'card_type'  => $card_type,
                        'amount'     => $card_balance,
                        'balance'    => $result_account_balance,
                        'type'       => 4,
                        'desc'       => $desc,
                        'ctime'      => $ctime
                    ]);
                    //记录钱包记录
                    Db::name('user_cash_log')->save([
                        'user_id'       => $user_id,
                        'type'          => 0,
                        'action_type'   => 4, //3=消费
                        'amount'        => $card_balance,
                        'balance'       => $result_user_balance,
                        'desc'          => $desc,
                        'card_type'     => $card_type,
                        'ctime'         => $ctime
                    ]);
                    $success_num += 1;
                    Db::commit();
                } catch (\Exception $e) {
                    Db::name('api_error')->save([
                        'user_id'       => $user_id,
                        'amount'        => $card_balance,
                        'amount_bank'   => $card_balance,
                        'type'          => 'manage_card_del',
                        'data_param'    => $e->getMessage(),
                        'ctime'         => getUtcTime()
                    ]);
                    Db::rollback();
                    break;
                }
            }
        }
        return $success_num;
    }

    /**
     * 返回layui的table所需要的格式
     * @param $post
     * @param $user_id
     * @return mixed
     * @throws \think\db\exception\DbException
     */
    public function tableDataDel($post)
    {
        $list_rows  = $post['limit'] ?? config('paginate.list_rows');
        $page       = $post['page'] ?? config('paginate.page');

        $where =[];
        $list = Db::name('cards_del')
            ->order('ctime desc')
            ->paginate(['list_rows' => $list_rows, 'page' => $page])
            ->toArray();
        return $result = [
            'code'  => 0,
            'msg'   => lang('get info success'),
            'data'  => $list['data'],
            'count' => $list['total'],
        ];
    }

    public static function checkCardBalanceApi($card_id , $action_type='searchExpDate', $return=false)
    {
        $card_list          = Db::name('cards')->where(['id' => $card_id])->find();
        $card_num           = $card_list['card_num'];
        $card_token         = $card_list['card_token'];
        $card_balance_total = $card_list['balance_account'];
        $card_balance       = $card_list['balance'];
        $card_status        = $card_list['status'];
        $user_id            = $card_list['user_id'];
        $card_type          = $card_list['card_type'];
        $bank_type          = $card_list['bank_type'];
        $check_status       = $card_list['check_status'];

        if ($check_status == 0) {
            return false;
        }
        $blog           = false;
        $ctime          = getUtcTime();

        if($bank_type == 3){
            $send_param         = [
                "user_id"       => $user_id,
                "card_num"      => $card_num,
                "cardGuid"      => $card_token,
                "action_type"   => "getCardDetail"
            ];
            $check_card_api = PublicApi::requestApi('Connexpay',$send_param);
            $return_blog    = $check_card_api['blog'];
            $return_list    = $check_card_api['list'];
            if($return_blog){
                $api_amount         = $return_list['availableBalance'];
                $api_amount_total   = $return_list['amountLimit'];
                $api_status         = $return_list['status'];
                if($api_status == 'Card - Active'){
                    $api_status = 1;
                }else if($api_status == 'Card - Suspended'){
                    $api_status = 2;
                }else if($api_status == 'Card - Deactivated'){
                    $api_status = 3;
                }
                if($api_status != $card_status){
                    Db::name('cards')->where(['id' => $card_id])->update(['status' => $api_status]);
                    Db::name('user_log')->save([
                        'user_id' => $user_id,
                        'state' => 'lss_update_card_status',
                        'ctime' => $ctime,
                        'params' => json_encode([
                            'card_num' => $card_num,
                            'old_status' => $card_status,
                            'new_status' => $api_status
                        ]),
                        'broswer' => $_SERVER['HTTP_USER_AGENT'] ?? '',
                        'ip' => get_client_ip(0, true)
                    ]);
                }
                $blog_num = 0;
                if($api_status == 3){
                    $blog_num = 1;
                }
                //银3 卡总金额与本地卡总金额不一致记录日志，已删除的卡是扣减等于1，其他是0
                if(abs($api_amount_total - $card_balance_total) != $blog_num) {
                    $error_type     = 'lss_card_total_comparison';
                    Db::name('api_error')->save([
                        'user_id'       => $user_id,
                        'amount'        => $card_balance_total,
                        'amount_bank'   => $api_amount_total,
                        'type'          => $error_type,
                        'data_param'    => json_encode([
                            'card_num'  => $card_num,
                            'balance'   =>$card_balance,
                            'api_balance'=>$api_amount,
                            'balance_account'=>$card_balance_total,
                            'api_balance_account'=>$api_amount_total
                        ]),
                        'ctime'         => $ctime
                    ]);
                }
                $re = false;

                if($api_amount - $card_balance != 0){
                    $re = Db::name('cards')->where(['id' => $card_id])->update(['balance' => $api_amount]);
                    Db::name('user_log')->save([
                        'user_id' => $user_id,
                        'state' => 'lss_update_card_balance',
                        'ctime' => $ctime,
                        'params' => json_encode([
                            'card_num' => $card_num,
                            'old_balance' => $card_balance,
                            'new_balance' => $api_amount
                        ]),
                        'broswer' => $_SERVER['HTTP_USER_AGENT'] ?? '',
                        'ip' => get_client_ip(0, true)
                    ]);
                }
                $blog = true;
            }
        }else{
            $send_param         = [
                "user_id"       => $user_id,
                "action_type"   => $action_type,
                "card_type"     => $card_type,
                "bank_type"     => $bank_type,
                "post_param"    => [
                    "card_num"  => $card_num,
                ]
            ];
            $check_card_api = PublicApi::requestApi('Comdata',$send_param);
            $return_blog    = $check_card_api['blog'];
            $return_list    = $check_card_api['list'];
            if($return_blog){
                $api_amount         = $return_list['cycleAmountLimitAvailable'];
                $api_amount_total   = $return_list['cycleAmountLimit'];

                if(($api_amount_total - $card_balance_total) != 0) {
                    $error_type     = 'card_total_comparison';
                    Db::name('api_error')->save([
                        'user_id'       => $user_id,
                        'amount'        => $card_balance_total,
                        'amount_bank'   => $api_amount_total,
                        'type'          => $error_type,
                        'data_param'    => json_encode([
                            'card_num'  => $card_num,
                            'balance'   =>$card_balance,
                            'api_balance'=>$api_amount,
                            'balance_account'=>$card_balance_total,
                            'api_balance_account'=>$api_amount_total
                        ]),
                        'ctime'         => $ctime
                    ]);
                }
                $api_card_status        = $return_list['cardStatus'];
                $card_update_array      = '';
                if($api_amount - $card_balance != 0){
                    $card_update_array      = ['balance' => $api_amount];
                }

                $api_card_status_num    = '';
                if($card_status != 3){ //用户已经删除的卡不能同步
                    if($api_card_status == 'A'){
                        $api_card_status_num = 1;
                    }else if($api_card_status == 'B'){
                        $api_card_status_num = 2;
                    }else if($api_card_status == 'F'){
                        $api_card_status_num = 4;
                    }
                    if(!empty($api_card_status_num)){
                        if($card_status != $api_card_status_num){
                            if(!empty($card_update_array)){
                                $card_update_array += ['status' => $api_card_status_num];
                            }else{
                                $card_update_array = ['status' => $api_card_status_num];
                            }
                        }
                    }
                }
                if(!empty($card_update_array)){
                    $re = Db::name('cards')->where(['id' => $card_id])->update($card_update_array);
                    if($re){
                        if(!empty($api_card_status_num)){
                            if($card_status != $api_card_status_num) {
                                Db::name('user_log')->save([
                                    'user_id' => $user_id,
                                    'state' => 'update_card_status_api',
                                    'ctime' => $ctime,
                                    'params' => json_encode([
                                        'card_num' => $card_num,
                                        'old_status' => $card_status,
                                        'new_status' => $api_card_status_num
                                    ]),
                                    'broswer' => $_SERVER['HTTP_USER_AGENT'] ?? '',
                                    'ip' => get_client_ip(0, true)
                                ]);
                            }
                        }
                        $blog = true;
                    }
                }
            }
        }
        if($action_type == "searchExpDate2"){
            if($blog){
                return json_encode([
                    'card_num'  => $card_num,
                    'amount'    => "{$card_balance} -> {$api_amount}"
                ]);
            }
        }
        if($return){
            return $blog;
        }
    }

    public static function saveTrans($user_id , $card_num ,$card_token,$card_status)
    {
        $send_tran_param         = [
            "user_id"       => $user_id,
            "card_num"      => $card_num,
            "cardGuid"      => $card_token,
            "action_type"   => "get_tran"
        ];
        $is_save = 0;
        //如果卡是删除状态，记录
        if($card_status == 3){
            $is_save = 1;
        }
        $card_tran_api = PublicApi::requestApi('Connexpay',$send_tran_param);
        $return_blog_tran    = $card_tran_api['blog'];
        $return_list_tran    = $card_tran_api['list'];
        if($return_blog_tran){
            if(isset($return_list_tran['transactions'])){
                $transactions_list = array_reverse($return_list_tran['transactions']);
                foreach ($transactions_list as $k_tran=>$v_tran){
                    $api_tran_status = $v_tran['status'];
                    $api_tran_type   = $v_tran['type'] ?? NULL;
                    $api_tran_token   = $v_tran['transactionGuid'];
                    $api_tran_ctime_real = substr(str_replace('T' , ' ' ,$v_tran['timestamp']) , 0 , 19);
                    $api_tran_ctime_CDT  = date('Y-m-d H:i:s',strtotime($api_tran_ctime_real . ' -5 hour'));
                    $api_tran_amount = $v_tran['amount'];
                    $approvalCode    = $v_tran['approvalCode'] ?? '';
                    $api_tran_shop   = $v_tran['merchantName'] ?? '';
                    $currencyCode    = $v_tran['currencyCode'] ?? '';
                    $cardAcceptorCountry    = $v_tran['cardAcceptorCountry'] ?? '';
                    $cardAcceptorMid = $v_tran['cardAcceptorMid'] ?? '';

                    if($api_tran_status == "PENDING"){
                        if($api_tran_type == 'authorization'){
                            $api_tran_status = 'Authorized';
                        }else{
                            //未遇到的类型,记录日志，金额未退到卡上,跳出循环,后期处理
                            //type = authorization.reversal | refund.authorization
                            self::saveErrorLog($user_id,'unfind_status_PENDING',$card_num,
                                json_encode(['status'=>'PENDING' , 'type'=>$api_tran_type]),$api_tran_ctime_real,
                                $api_tran_amount,$approvalCode
                            );
                            continue;
                        }
                    }else if($api_tran_status == "DECLINED"){
                        if($api_tran_type == 'authorization'){
                            //正常消费拒绝
                            $api_tran_status = 'Declined';
                        }else{
                            //未遇到的类型,记录日志，跳出循环,后期处理
                            //type = refund.authorization | authorization.clearing.chargeback
                            //       authorization.clearing.chargeback.completed
                            self::saveErrorLog($user_id,'unfind_status_DECLINED',$card_num,
                                json_encode(['status'=>'DECLINED' , 'type'=>$api_tran_type]),$api_tran_ctime_real,
                                $api_tran_amount,$approvalCode
                            );
                            continue;
                        }
                    }else if($api_tran_status == "COMPLETION"){
                        if($api_tran_type == 'authorization.clearing'){
                            //正常消费结算
                            $api_tran_status = 'Posted';
                        }else if($api_tran_type == 'refund.authorization.clearing'){
                            //正常退款结算
                            $api_tran_status = 'Credit';
                        }else{
                            //未遇到的类型,记录日志，跳出循环,后期处理
                            //type = refund | authorization.clearing.representment
                            //       authorization.clearing.chargeback.completed | authorization.clearing.chargeback
                            self::saveErrorLog($user_id,'unfind_status_COMPLETION',$card_num,
                                json_encode(['status'=>'COMPLETION' , 'type'=>$api_tran_type]),$api_tran_ctime_real,
                                $api_tran_amount,$approvalCode
                            );
                            continue;
                        }
                    }else if($api_tran_status == "CLEARED"){
                        if($api_tran_type == 'authorization.reversal'){
                            //正常撤销
                            $api_tran_status = 'Reversal';
                        }else if($api_tran_type == 'authorization.reversal.issuerexpiration') {
                            $api_tran_status = 'Reversal';
                        }else{
                            //未遇到的类型,记录日志，跳出循环,后期处理
                            //type = authorization | authorization.clearing.chargeback.reversal
                            //       authorization.reversal.issuerexpiration | refund.authorization.reversal
                            self::saveErrorLog($user_id,'unfind_status_CLEARED',$card_num,
                                json_encode(['status'=>'CLEARED' , 'type'=>$api_tran_type]),$api_tran_ctime_real,
                                $api_tran_amount,$approvalCode
                            );
                            continue;
                        }
                    }

                    $correctiveAction= "";
                    //如果有appCode 那么就存在pending post Credit
                    if(!empty($approvalCode)){
                        //appCode是唯一的，如果pending不存在那么存储
                        if($api_tran_status == 'Authorized'){
                            $current_tran_list = Db::name('cards_trans')->where([
                                'app_code'      =>  $approvalCode,
                                'card_num'      =>  $card_num,
                                'bank_type'     =>  3
                            ])->find();
                            if($current_tran_list) {
                            }else{
                                $insert_auth = [
                                    'user_id'       => $user_id,
                                    'app_code'      => $approvalCode,
                                    'card_num'      => $card_num,
                                    'tran_status'   => $api_tran_status,
                                    'amount_auth'   => $api_tran_amount,
                                    'reversal_flag' => 'N',
                                    'desc'          => $correctiveAction,
                                    'shopping'      => $api_tran_shop,
                                    'ctime'         => $api_tran_ctime_CDT,
                                    'ctime_real'    => $api_tran_ctime_real,
                                    'bank_type'     => 3,
                                    'tran_token'    => $api_tran_token,
                                    'currencyCode'  => $currencyCode,
                                    'country'       => $cardAcceptorCountry,
                                    'mid'           => $cardAcceptorMid
                                ];
                                $e = Db::name('cards_trans')->save($insert_auth);

                                if($is_save == 1){
                                    Db::name('cards_trans_other')->save($insert_auth);
                                }
                            }
                        }else
                            if($api_tran_status == 'Posted'){
                            //如果是posted那么就是结算完成，更新这条appCode记录
                            if($approvalCode == 'XXXXXX'){
                                $current_tran_list = Db::name('cards_trans')->where([
                                    'tran_token'    =>  $api_tran_token,
                                    'card_num'      =>  $card_num,
                                    'bank_type'     =>  3
                                ])->find();
                                if(empty($current_tran_list)){
                                    $insert_auth = [
                                        'user_id'       => $user_id,
                                        'app_code'      => $approvalCode,
                                        'card_num'      => $card_num,
                                        'tran_status'   => $api_tran_status,
                                        'amount_auth'   => $api_tran_amount,
                                        'reversal_flag' => 'N',
                                        'desc'          => $correctiveAction,
                                        'shopping'      => $api_tran_shop,
                                        'ctime'         => $api_tran_ctime_CDT,
                                        'ctime_real'    => $api_tran_ctime_real,
                                        'utime'         => $api_tran_ctime_CDT,
                                        'utime_real'    => $api_tran_ctime_real,
                                        'bank_type'     => 3,
                                        'tran_token'    => $api_tran_token,
                                        'currencyCode'  => $currencyCode,
                                        'country'       => $cardAcceptorCountry,
                                        'mid'           => $cardAcceptorMid
                                    ];
                                    Db::name('cards_trans')->save($insert_auth);
                                }
                            }else{
                                $current_tran_list = Db::name('cards_trans')->where([
                                    'app_code'  =>  $approvalCode,
                                    'card_num'  =>  $card_num,
                                    'bank_type' =>  3
                                ])->find();
                                if($current_tran_list){
                                    $current_tran_id = $current_tran_list['id'];
                                    $tran_status     = $current_tran_list['tran_status'];
                                    if($tran_status == 'Authorized'){
                                        Db::name('cards_trans')->where(['id'=>$current_tran_id])->update([
                                            'tran_status'   => $api_tran_status,
                                            'amount_post'   => $api_tran_amount,
                                            'utime'         => $api_tran_ctime_CDT,
                                            'utime_real'    => $api_tran_ctime_real,
                                        ]);
                                    }
                                }
                            }
                        }else
                            if($api_tran_status == 'Credit'){
                                $current_tran_list = Db::name('cards_trans')->where([
                                    'tran_token'    =>  $api_tran_token,
                                    'card_num'      =>  $card_num,
                                    'bank_type'     =>  3,
                                ])->where("ctime > '2024-01-01 00:00:00'")->find();
                                if($current_tran_list){
                                    //如果是Credit那么就是结算完成，更新这条appCode记录
                                    $current_tran_id = $current_tran_list['id'];
                                    $tran_status     = $current_tran_list['tran_status'];
                                    if($tran_status == 'Authorized'){
                                        Db::name('cards_trans')->where(['id'=>$current_tran_id])->update([
                                            'tran_status'   => $api_tran_status,
                                            'amount_post'   => $api_tran_amount,
                                            'utime'         => $api_tran_ctime_CDT,
                                            'utime_real'    => $api_tran_ctime_real,
                                        ]);
                                    }
                                    //退款收取 手续费----------------------------------start
                                    $abs_amount = abs($api_tran_amount);
                                    $check_credit = Db::name('cards_trans_credit_lss')->where([
                                        'card_num'      => $card_num,
                                        'tran_token'    =>  $api_tran_token,
                                    ])->where("ctime > '2024-01-01 00:00:00'")->find();
                                    if(empty($check_credit)){
                                        $credit_add = [
                                            'card_num'      => $card_num,
                                            'amount'        => $abs_amount,
                                            'ctime'         => $api_tran_ctime_CDT,
                                            'app_code'      => $approvalCode,
                                            'user_id'       => $user_id,
                                            'shopping'      => $api_tran_shop,
                                            'tran_token'    => $api_tran_token,
                                            'card_status'   => $card_status
                                        ];
                                        if($card_status != 3){
                                            $credit_result = CardsTransCredit::endCredit([
                                                'card_num'      =>  $card_num,
                                                'user_id'       =>  $user_id,
                                                'credit_amount' =>  $abs_amount,
                                                'shopping'      =>  $api_tran_shop,
                                            ] , 2);
                                            if($credit_result){
                                                $credit_server_set = UserSet::getCardSet($user_id);
                                                $card_type         = substr($card_num , 0,6);
                                                $credit_server_set_rate = $credit_server_set[3][$card_type]['rate_refund'];
                                                $credit_server_amount = getSprintf(round($abs_amount * $credit_server_set_rate,2));
                                                $credit_add += [
                                                    'credit_status' => 1,
                                                    'utime' => getUtcTime(),
                                                    'server_amount' => $credit_server_amount
                                                ];
                                            }
                                        }
                                        Db::name('cards_trans_credit_lss')->save($credit_add);
                                    }
                                    //退款收取 手续费----------------------------------end
                                }else{
                                    $insert_credit = [
                                        'user_id'       => $user_id,
                                        'app_code'      => $approvalCode,
                                        'card_num'      => $card_num,
                                        'tran_status'   => $api_tran_status,
                                        'amount_auth'   => $api_tran_amount,
                                        'reversal_flag' => 'N',
                                        'desc'          => $correctiveAction,
                                        'shopping'      => $api_tran_shop,
                                        'ctime'         => $api_tran_ctime_CDT,
                                        'ctime_real'    => $api_tran_ctime_real,
                                        'amount_post'   => $api_tran_amount,
                                        'utime'         => $api_tran_ctime_CDT,
                                        'utime_real'    => $api_tran_ctime_real,
                                        'bank_type'     => 3,
                                        'tran_token'    => $api_tran_token,
                                        'mid'           => $cardAcceptorMid
                                    ];
                                    Db::name('cards_trans')->save($insert_credit);

                                    if($is_save == 1){
                                        Db::name('cards_trans_other')->save($insert_credit);
                                    }
                                }
                            }else{
                                if($api_tran_status == 'Reversal'){
                                    if($api_tran_amount - 0 != 0){
                                        $current_tran_list = Db::name('cards_trans')->where([
                                            'app_code'  =>  $approvalCode,
                                            'bank_type' =>  3,
                                            'tran_token'=>  $api_tran_token
                                        ])->find();
                                        if(empty($current_tran_list)){
                                            Db::name('cards_trans')->save([
                                                'user_id'       => $user_id,
                                                'app_code'      => $approvalCode,
                                                'card_num'      => $card_num,
                                                'tran_status'   => $api_tran_status,
                                                'amount_auth'   => $api_tran_amount,
                                                'reversal_flag' => 'N',
                                                'desc'          => $correctiveAction,
                                                'shopping'      => $api_tran_shop,
                                                'ctime'         => $api_tran_ctime_CDT,
                                                'ctime_real'    => $api_tran_ctime_real,
                                                'bank_type'     => 3,
                                                'reversal_expired'  => 1,
                                                'tran_token'    => $api_tran_token,
                                                'mid'           => $cardAcceptorMid
                                            ]);
                                        }
                                    }
                                }
                            }
                    }else{
                        $current_tran_list = Db::name('cards_trans')->where([
                            'ctime_real'=>$api_tran_ctime_real,
                            'bank_type'=>3
                        ])->find();
                        if(empty($current_tran_list)){
                            $save_param = [
                                'user_id'       => $user_id,
                                'app_code'      => $approvalCode,
                                'card_num'      => $card_num,
                                'tran_status'   => $api_tran_status,
                                'amount_auth'   => $api_tran_amount,
                                'reversal_flag' => 'N',
                                'shopping'      => $api_tran_shop,
                                'ctime'         => $api_tran_ctime_CDT,
                                'ctime_real'    => $api_tran_ctime_real,
                                'bank_type'     => 3,
                                'tran_token'    => $api_tran_token,
                                'mid'           => $cardAcceptorMid
                            ];
                            if($api_tran_status == 'Declined'){
                                $correctiveAction = $v_tran['description'] ?? '';
                            }else if($api_tran_status == 'Credit'){
                                $save_param += [
                                    'amount_post'   => $api_tran_amount,
                                    'utime'         => $api_tran_ctime_CDT,
                                    'utime_real'    => $api_tran_ctime_real
                                ];
                            }
                            $save_param += [
                                'desc'          => $correctiveAction
                            ];
                            Db::name('cards_trans')->save($save_param);
                        }
                    }
                }
            }
        }
        self::checkBank3($user_id , $card_num);
    }

    private static function checkBank3($user_id , $card_num)
    {
        $list = Db::name('cards_trans')
            ->field('count(*) num , app_code')
            ->where("app_code != ''
            and bank_type=3
            and user_id     = {$user_id}
            and card_num    = {$card_num}")
            ->group('app_code')->select()->toArray();
        if($list){
            foreach ($list as $k=>$v) {
                $num = $v['num'];
                if ($num > 1) {
                    $post_list = Db::name('cards_trans')
                        ->where([
                                'app_code'=>$v['app_code'] ,
                                'tran_status'=>'Posted' ,
                                'bank_type' => 3,
                                'user_id' => $user_id,
                                'card_num'=> $card_num
                            ]
                        )->find();
                    if($post_list){
                        Db::name('cards_trans')
                            ->where([
                                'app_code'=>$v['app_code'] ,
                                'tran_status'=>'Authorized' ,
                                'bank_type' => 3,
                                'user_id' => $user_id,
                                'card_num'=> $card_num
                            ])->delete();
                    }
                }
            }
        }
    }

    private static function saveErrorLog($user_id,$type,$card_num,$desc,$ctime,$amount,$appCode)
    {
        $list = Db::name('lss_api_error')->where([
            'user_id'       => $user_id,
            'card_num'      => $card_num,
            'type'          => $type,
            'param'         => $desc,
            'amount'        => $amount,
            'app_code'      => $appCode
        ])->find();
        if(!empty($list)){
            if($amount - 0 != 0){
                Db::name('lss_api_error')->save([
                    'user_id'       => $user_id,
                    'type'          => $type,
                    'card_num'      => $card_num,
                    'param'         => $desc,
                    'ctime'         => $ctime,
                    'amount'        => $amount,
                    'app_code'      => $appCode
                ]);
            }
        }
    }

    /**
     * 银12，通过查询api获取最新的卡余额,并更新
     * @param $card_list
     * @return array
     */
    public static function apiUpCardBalance($card_list)
    {
        $ctime              = getUtcTime();
        $card_id            = $card_list['id'];
        $user_id            = $card_list['user_id'];
        $card_status        = $card_list['status'];
        $card_type          = $card_list['card_type'];
        $balance_account    = $card_list['balance_account'];
        $bank_type          = $card_list['bank_type'];
        $card_balance       = $card_list['balance'];
        $card_num           = $card_list['card_num'];

        $cycleAmountLimitUsed   = 0.00;
        $cycleAmountLimitHold   = 0.00;
        $api_amount             = 0.00;
        $api_amount_total       = 0.00;

        $send_param         = [
            "user_id"       => $user_id,
            "action_type"   => "searchExpDate2",
            "card_type"     => $card_type,
            "bank_type"     => $bank_type,
            "post_param"    => [
                "card_num"  => $card_num,
            ]
        ];
        $check_card_api = PublicApi::requestApi('Comdata',$send_param);
        $return_blog    = $check_card_api['blog'];
        $return_list    = $check_card_api['list'];
        if($return_blog) {
            $api_amount             = $return_list['cycleAmountLimitAvailable'];
            $api_amount_total       = $return_list['cycleAmountLimit'];
            $cycleAmountLimitUsed   = $return_list['cycleAmountLimitUsed'];
            $cycleAmountLimitHold   = $return_list['cycleAmountLimitHold'];
            if($api_amount_total - $balance_account != 0){
                $api_error_list = Db::name('api_error_cd')
                    ->where([
                        'card_num'      => $card_num,
                        'amount'        => $balance_account,
                        'amount_bank'   => $api_amount_total,
                    ])->find();
                if(empty($api_error_list)){
                    Db::name('api_error_cd')->save([
                        'user_id'       => $user_id,
                        'card_num'      => $card_num,
                        'amount'        => $balance_account,
                        'amount_bank'   => $api_amount_total,
                        'type'          => 'card_limit_diff',
                        'ctime'         => $ctime
                    ]);
                }
            }
            $api_card_status        = $return_list['cardStatus'];
            $card_update_array      = '';
            if($api_amount - $card_balance != 0){
                $card_update_array      = ['balance' => $api_amount];
            }

            $api_card_status_num    = '';
            if($card_status != 3){ //用户已经删除的卡不能同步
                if($api_card_status == 'A'){
                    $api_card_status_num = 1;
                }else if($api_card_status == 'B'){
                    $api_card_status_num = 2;
                }else if($api_card_status == 'F'){
                    $api_card_status_num = 4;
                }
                if(!empty($api_card_status_num)){
                    if($card_status != $api_card_status_num){
                        if(!empty($card_update_array)){
                            $card_update_array += ['status' => $api_card_status_num];
                        }else{
                            $card_update_array = ['status' => $api_card_status_num];
                        }
                    }
                }
            }
            if(!empty($card_update_array)){
                Db::name('cards')->where(['id' => $card_id])->update($card_update_array);
                Db::name('admin_up_log')->save([
                    'user_id'   => $user_id,
                    'card_num'  => $card_num,
                    'type'      => 'up_card_status_balance',
                    'bank_type' => 'cd',
                    'params' => json_encode([
                        'old_status'        => $card_status,
                        'new_status'        => $api_card_status_num,
                        'old_card_balance'  =>$card_balance,
                        'new_card_balance'  =>$api_amount
                    ]),
                    'ctime' => $ctime,
                ]);
            }
        }
        return [
            'cycleAmountLimitUsed'  => $cycleAmountLimitUsed,
            'cycleAmountLimitHold'  => $cycleAmountLimitHold,
            'api_amount'            => $api_amount,
            'api_amount_total'      => $api_amount_total
        ];
    }

    public function adminCardBalance($type,$data)
    {
        $card_id    = $data['card_id'];
        $amount     = $data['amount'];
        $user_id    = $data['user_id'];
        $manage_id  = $data['manage_id'];

        //获取当前用户余额
        $user_list              = Db::name('user')->find($user_id);
        $user_balance           = $user_list['balance'];
        $user_name              = $user_list['username'];
        //增加进程是否开始，防止重复建卡 //并且时间时间是10秒
        $redis_key              = 'user_update_balance_' . $user_name;
        Cache::store('redis')->set($redis_key , getUtcTime() , 10);
        //可能有卡消费了 ，需要再通过接口查询一下卡余额；
        self::checkCardBalanceApi($card_id);
        //这里可能卡余额更新了 再查询一次卡信息
        $card_list              = Db::name('cards')->find($card_id);

        $card_balance           = $card_list['balance'];    //当前卡可用余额
        $balance_account        = $card_list['balance_account'];//当前卡账户余额
        $card_num               = $card_list['card_num'];
        $card_num4              = substr($card_num , -4);
        $card_token             = $card_list['card_token'];
        $is_del                 = $card_list['is_del'];
        $card_type              = $card_list['card_type'];
        $card_server_amount     = $card_list['server_amount'];
        $bank_type              = $card_list['bank_type'];

        $ctime                  = getUtcTime();
        if($is_del == 1){
            Cache::store('redis')->delete($redis_key);
            return false;
        }
        //获取卡操作记录的最近的一笔卡限额
        $card_amount_limit_list = Db::name('cards_log')->where(['card_token' => $card_token])->order('id desc')->find();
        $card_amount_limit      = $card_amount_limit_list['balance'];
        //卡列表记录的卡限额 和 卡操作记录的卡限额不一致 返回失败
        if($balance_account - $card_amount_limit !=0){
            Cache::store('redis')->delete($redis_key);
            if($bank_type == 3){
                $data       = [
                    "user_id"       => $user_id,
                    "action_type"   => "card_suspended",
                    "cardGuid"      => $card_token,
                    "card_num"      => $card_num,
                    "request_data"  => [
                        "Activated" => false
                    ]
                ];
                $update_result = PublicApi::requestApi('Connexpay' , $data);
            }else{
                $data       = [
                    "user_id"       => $user_id,
                    "action_type"   => "card_suspended",
                    "card_type"     => $card_type,
                    "bank_type"     => $bank_type,
                    "post_param"    => [
                        "card_num"       => $card_num
                    ]
                ];
                $update_result = PublicApi::requestApi('Comdata' , $data);
            }
            $update_result_blog = $update_result['blog'];
            $ice_success = false;
            if($update_result_blog){
                $update_where = [
                    'status'    => 2,
                    'is_action' => 1,   //is_action  = 1 冻结后不能激活 | = 0 默认
                    'utime' =>  getUtcTime()
                ];
                //更新卡列表状态
                Db::name('cards')->where(['id'=> $card_id])->update($update_where);
                $ice_success = true;
                //记录会员操作日志
                $logModel = new UserLog();
                $logModel->setLog($user_id , "card_suspended" , [
                    'card_num' => $card_num ,
                    'desc'=>'卡操作记录卡限额和卡列表记录不一致',
                    'amount' =>  $balance_account . '___' . $card_amount_limit
                ]);
            }
            Db::name('action_error')->save([
                'user_id' => $user_id,
                'type'    => $type,   //类型场景
                'card_num'=> $card_num,
                'remark'  => '卡操作记录卡限额和卡列表记录不一致',
                'desc'    =>
                    "balance_account:{$balance_account} , 
                    card_amount_limit:{$card_amount_limit},
                    ice_result:{$ice_success}", //冻结接口结果
                'ctime'   => $ctime
            ]);
            return false;
        }

        $error_msg              = '';
        $blog                   = false;

        //deduct|add CardBalance
        if($type == 'add_card_balance'){
            $result_user_balance    = $user_balance - $amount;
            $result_card_balance    = $card_balance + $amount;
            $result_account_balance = $balance_account + $amount;
            $desc                   = "增加卡({$card_type} *** {$card_num4})余额";
            $card_log_type          = 2; //2-增加余额;3-减少余额
            $user_cash_log_type     = 1; //类型 0,Credit|1,Debit
        }else{
            $result_user_balance    = $user_balance + $amount;
            $result_card_balance    = $card_balance - $amount;
            if($result_card_balance <= 0){
                Cache::store('redis')->delete($redis_key);
                return false;
            }
            $result_account_balance = $balance_account - $amount;
            $desc                   = "为修正账户负余额，系统减少卡({$card_type} *** {$card_num4})余额";
            $card_log_type          = 3;
            $user_cash_log_type     = 0;
        }
        if($bank_type == 1 || $bank_type ==2){
            $update_card_param      = [
                "user_id"       => $user_id,
                "action_type"   => $type,
                "card_type"     => $card_type,
                "bank_type"     => $bank_type,
                "post_param"  => [
                    "card_num"              => $card_num,
                    "card_balance"          => getSprintf(round($result_account_balance, 2))
                ]
            ];
            $create_card_api= PublicApi::requestApi('Comdata',$update_card_param);
            $return_blog    = $create_card_api['blog'];
        }else if($bank_type == 3){
            $update_card_param      = [
                "user_id"       => $user_id,
                "action_type"   => $type,
                "card_num"      => $card_num,
                "cardGuid"      => $card_token,
                "request_data"  => [
                    "AmountLimit" => getSprintf(round($result_account_balance, 2))
                ]
            ];
            $create_card_api= PublicApi::requestApi('Connexpay',$update_card_param);
            $return_blog    = $create_card_api['blog'];
        }
        if($return_blog){
            Db::startTrans();
            try{
                //记录卡总金额变化
                Db::name('cards_log')->save([
                    'card_token' => $card_token,
                    'amount' => $amount,
                    'balance' => $result_account_balance,
                    'type' => $card_log_type,
                    'desc' => $desc,
                    'card_type' => $card_type,
                    'ctime' => $ctime
                ]);
                //记录钱包记录
                Db::name('user_cash_log')->save([
                    'user_id' => $user_id,
                    'type' => $user_cash_log_type,
                    'action_type' => 5, //3=消费
                    'amount' => $amount,
                    'balance' => $result_user_balance,
                    'desc' => $desc,
                    'card_type' => $card_type,
                    'ctime' => $ctime
                ]);
                if ($type == 'add_card_balance') {
                    $rate = $data['rate'];
                    $server_amount = $amount * $rate;
                    $result_user_balance -= $server_amount;
                    $card_server_amount += $server_amount;
                    //记录钱包卡充值服务费记录
                    Db::name('user_cash_log')->save([
                        'user_id' => $user_id,
                        'type' => $user_cash_log_type,
                        'action_type' => 5, //3=消费
                        'amount' => $server_amount,
                        'balance' => $result_user_balance,
                        'desc' => "充值服务费 ({$card_type} *** {$card_num4})",
                        'card_type' => $card_type,
                        'ctime' => $ctime
                    ]);
                }
                //更新公司用户余额
                Db::name('user')->where([
                    'id' => $user_id
                ])->update(['balance' => $result_user_balance]);
                //更新卡余额
                Db::name('cards')->where([
                    'id' => $card_id
                ])->update([
                    'balance'           => $result_card_balance,
                    'balance_account'   => $result_account_balance,
                    'server_amount'     => $card_server_amount
                ]);
                $blog = true;
                Db::commit();
            } catch (\Exception $e) {
                Cache::store('redis')->delete($redis_key);
                $blog       = false;
                $error_msg  = $e->getMessage();
                Db::rollback();
            }
        }
        //记录用户操作
        ManageLog::saveManageLog([
            'manage_id' => $manage_id,
            'desc'      => 'debit_card_balance',
            'time'      => getUtcTime(),
            'content'   => json_encode([
                'card_num' => $card_num,
                'username' => $user_name,
                'amount'   => $amount
            ])
        ]);
        return $blog;
    }
}